package com.yuwubao.hz_International.controllers.sys;

import com.yuwubao.hz_International.util.Const;
import com.yuwubao.hz_International.util.RestApiResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * Created by yangyu on 2018/2/1.
 */
@RestController
@RequestMapping("/resource")
@CrossOrigin
@Api(value = "后台接口")
public class FileUploadController {

    private final static Logger logger = LoggerFactory.getLogger(FileUploadController.class);

    /**
     * 将上传的图片保存到本地
     * @param file 上传的文件
     * @return
     */
    @PostMapping("/upload")
    @ApiOperation(value = "将上传的图片保存到本地")
    public RestApiResponse<String> saveFile(MultipartFile file) {
        RestApiResponse<String> result = new RestApiResponse<String>();
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String time = sdf.format(new Date());
            String path = null;
            String sysName = System.getProperties().getProperty("os.name");
            String separator = System.getProperties().getProperty("file.separator");
            if (sysName.contains("Linux")) {
                path = separator + "tmp" + separator + "img" + separator + time + separator;
            } else {
                path = "E:" + separator + "img" + separator + time + separator;
            }
            File f = new File(path);
            if (!f.exists()) {
                f.mkdirs();
            }
            String filename = file.getOriginalFilename();
            String suffix = filename.substring(filename.lastIndexOf('.'));
            String uuid = UUID.randomUUID().toString().replace("-", "");
            filename = uuid + suffix;
            String visit = "img/"+time+"/" + filename;
            file.transferTo(new File(path  + filename));
            //String address = ThinkTankUtil.getLocalHostLANAddress().getHostAddress();
            String ip= "http://47.104.170.54/";
            result.successResponse(Const.SUCCESS, ip+visit,"上传成功");
        } catch (Exception e) {
            logger.warn("文件上传失败", e);
            result.failedApiResponse(Const.FAILED, "文件上传失败");
        }
        return result;
    }
}
